package com.cloudkinto.service.order.delayTask;

import cn.hutool.core.thread.ThreadUtil;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.service.order.OrderAmazonVdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;

/**
 * 延迟任务队列
 *
 * @author long
 */
@Component
public class DelayTaskService {

    private DelayTaskService delayTaskService;

    @Autowired
    @Lazy
    private OrderAmazonVdfService vdfService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 创建延时队列
     */
    private final DelayQueue<GetShippingLabelDelay> delayQueue = new DelayQueue<>();

    @PostConstruct
    private void init() {
        // 当前类初始化执行这个方法, 循环取 队列中的任务
        delayTaskService = this;
        ThreadUtil.execute(() -> {
            while (true) {
                try {
                    GetShippingLabelDelay task = delayQueue.take();
                    vdfService.getVdfShippingLabel(task.getDataMap(), false, true);
                    redisTemplate.opsForHash().delete(SysConstant.VDF_SHIPPING_LABEL_DELAY_KEY, task.getTaskTimeStamp());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void addTask(GetShippingLabelDelay task) {
        if (delayQueue.contains(task)) {
            return;
        }
        delayQueue.add(task);
        redisTemplate.opsForHash().put(SysConstant.VDF_SHIPPING_LABEL_DELAY_KEY, task.getTaskTimeStamp(), task);
    }

    public void removeTask(GetShippingLabelDelay task) {
        boolean remove = delayQueue.remove(task);
        if (remove) {
            redisTemplate.opsForHash().delete(SysConstant.VDF_SHIPPING_LABEL_DELAY_KEY, task.getTaskTimeStamp());
        }
    }

}

